package cn.com.aiouyi.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.com.aiouyi.dao.NavigationDao;
import cn.com.aiouyi.entity.Navigation;
import cn.com.aiouyi.service.LinkService;
import cn.com.aiouyi.service.NavigationPositionService;
import cn.com.aiouyi.service.NavigationService;
import cn.com.aiouyi.util.AssertUtils;

/**
 * Service - 导航
 * @author hanson
 *
 */
@Service("navigationServiceImpl")
public class NavigationServiceImpl extends BaseServiceImpl<Navigation, Long> implements NavigationService{

	@Resource(name = "navigationDaoImpl")
	private NavigationDao navigationDao;
	@Resource(name = "navigationPositionServiceImpl")
	private NavigationPositionService navigationPositionService;
	@Resource(name = "linkServiceImpl")
	private LinkService linkService;
	
	@Override
	public Navigation save(Navigation navigation) {
		AssertUtils.notNull(navigation);

		linkService.validAndFill(navigation.getLink());
		
		setValue(navigation);
		return super.save(navigation);
	}

	@Override
	public Navigation update(Navigation navigation) {
		AssertUtils.notNull(navigation);
		
		if(navigation.getParent() != null){
			navigation.setNavigationPosition(navigation.getParent().getNavigationPosition());
		}
		// 两者不能同时null
		if(navigation.getNavigationPosition() == null){
			throw new IllegalArgumentException("导航位不能为空");
		}
		
		linkService.validAndFill(navigation.getLink());
		
		setValue(navigation);
		for (Navigation children : navigationDao.findChildren(navigation, true, null)) {
			setValue(children);
		}
		return super.update(navigation);
	}
	
	@Transactional(readOnly = true)
	public List<Navigation> findChildren(Navigation navigation, boolean recursive, Integer count) {
		return navigationDao.findChildren(navigation, recursive, count);
	}
	
	@Transactional(readOnly = true)
	public List<Navigation> findTree() {
		return navigationDao.findChildren(null, true, null);
	}
	
	/**
	 * 设置值
	 * @param navigation
	 */
	private void setValue(Navigation navigation) {
		if (navigation == null) {
			return;
		}
		Navigation parent = navigation.getParent();
		if (parent != null) {
			navigation.setTreePath(parent.getTreePath() + parent.getId() + Navigation.TREE_PATH_SEPARATOR);
		} else {
			navigation.setTreePath(Navigation.TREE_PATH_SEPARATOR);
		}
		navigation.setGrade(navigation.getParentIds().length);
	}
}
